package com.ecar.mp.servlet;

import org.apache.log4j.Logger;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class UploadServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private static final Logger logger = Logger.getLogger(UploadServlet.class);
	private String filePath;
	private static final long UPLOAD_SIZE_LIMIT = 5242880;        // 1024 * 1024 * 5 = 5MB

	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		filePath = config.getInitParameter("filepath");
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		PrintWriter writer = response.getWriter();
		writer.write("call POST with multipart form data");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
																						   IOException {
//		if (!ServletFileUpload.isMultipartContent(request)) {
//			throw new IllegalArgumentException(
//					"Request is not multipart, please 'multipart/form-data' enctype for your form.");
//		}

//		PropertyUtil propertyUtil = (PropertyUtil) SpringContextUtil.getBean("propertyUtil");
//		String host = propertyUtil.getValue("config.host.url");
//
//		ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());
//		response.setContentType("text/plain;charset=UTF-8");
//		response.setCharacterEncoding("UTF-8");
//		PrintWriter writer = response.getWriter();
//		// DataBean<?> responseBean = new DataBean();
//
//		String attributeName = request.getParameter("attributeName");
//		logger.debug("attributeName:" + attributeName);
//
//		SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMdd");
//		ServletContext context = getServletContext();
//		// 获取绝对路径和相对路径
//		String dir = context.getRealPath(filePath) + "/" + attributeName + "/" + dateformat.format(new Date());
//		String relativePath = "/mp/" + dir.substring(dir.lastIndexOf("upload"));
//		// 返回使用JSON对象，避免手工拼接字符串出错
//		JSONObject ret = new JSONObject();
//		try {
//			if (attributeName == null) {
//				ret.put("code", 400);
//				ret.put("message", "上传参数错误！");
//				writer.write(ret.toString());
//			} else if (attributeName.equalsIgnoreCase("apk")) {
//				List<FileItem> items = uploadHandler.parseRequest(request);
//				for (FileItem item : items) {
//					if (!item.isFormField() && item.getSize() > 0) {
//						if (item.getSize() > 524288000) {
//							ret.put("code", 400);
//							ret.put("message", "上传文件大小超过限制，文件不能大于500MB！");
//							writer.write(ret.toString());
//							break;
//						}
//
//						logger.debug(item.getName());
//						String name = new Date().getTime() + "_" + item.getName();
//
//						// 检查文件格式
//						if (!name.endsWith(".apk")) {
//							ret.put("code", 400);
//							ret.put("message", "上传文件格式错误，请上传apk文件包！");
//							writer.write(ret.toString());
//							break;
//						}
//
//						// 先创建目录
//						File directory = new File(dir);
//						if (!directory.exists() && !directory.isDirectory()) {
//							directory.mkdirs();
//						}
//
//						File file = new File(dir, name);
//						item.write(file);
//
//						long uploaddate = System.currentTimeMillis();
//
//						// 使用JSON对象，规范返回的字符串
//						ret.put("code", 200);
//						ret.put("filePath",host + relativePath + "/" + name);
//						ret.put("name", item.getName());
//						ret.put("size", item.getSize());
//						ret.put("uploaddate", uploaddate);
//						ret.put("attributeName", attributeName);
//						writer.write(ret.toString());
//						break;
//					}
//				}
//			} else {
//				List<FileItem> items = uploadHandler.parseRequest(request);
//				for (FileItem item : items) {
//					if (!item.isFormField() && item.getSize() > 0) {
//						if (item.getSize() > UPLOAD_SIZE_LIMIT) {
//							ret.put("code", 400);
//							ret.put("message", "上传文件大小超过限制，文件不能大于5MB！");
//							writer.write(ret.toString());
//							break;
//						}
//
//						logger.debug(item.getName());
//						String name = new Date().getTime() + "_" + item.getName();
//
//						// 先创建目录
//						File directory = new File(dir);
//						if (!directory.exists() && !directory.isDirectory()) {
//							directory.mkdirs();
//						}
//
//						File file = new File(dir, name);
//						item.write(file);
//
//						long uploaddate = System.currentTimeMillis();
//
//						ret.put("code", 200);
//						ret.put("filePath",host + relativePath + "/" + name);
//						ret.put("name", item.getName());
//						ret.put("size", item.getSize());
//						ret.put("uploaddate", uploaddate);
//						ret.put("attributeName", attributeName);
//						writer.write(ret.toString());
//
//						/*
//						 * Long maxSize = Long.valueOf(StaticCacheService
//						 * .getSettingProperty("upload.file.maxSize"));
//						 */
//						// Long maxSize = Long.valueOf(1024 * 400);
//						/*
//						 * if (item.getSize() >= maxSize) { file.delete(); Map
//						 * map = new HashMap(); map.put("maxSize", maxSize);
//						 *
//						 * //responseBean.setCode(1412);
//						 * //responseBean.setParam(map); JsonBeanUtils utils =
//						 * new JsonBeanUtils();
//						 * writer.write(utils.toJson(responseBean)); } else {
//						 * /*sendUploadContractRequest(writer, file,
//						 * item.getName(), item.getSize(), tablename, tableid);
//						 * }
//						 */
//						break;
//					}
//				}
//			}
//		} catch (FileUploadException e) {
//			logger.error(e.getMessage(), e);
//			throw new RuntimeException(e);
//		} catch (Exception e) {
//			logger.error(e.getMessage(), e);
//			throw new RuntimeException(e);
//		} finally {
//			writer.close();
//		}
	}

	/*
	 * public void sendUploadContractRequest(PrintWriter writer, File file,
	 * String fileName, long fileSize, String tabName, String tabId) throws
	 * HttpException, IOException {
	 * 
	 * HttpClient httpclient = new HttpClient(); String url = StaticCacheService
	 * .getSettingProperty("web2service.upload.url");
	 * httpclient.getParams().setParameter(
	 * HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8"); PostMethod httpPost =
	 * new PostMethod(url) {
	 * 
	 * @Override public String getRequestCharSet() { return "UTF-8"; } };
	 * logger.debug(fileName); Part[] parts = { new FilePart("file", fileName,
	 * file, null, "UTF-8"), new StringPart("tablename", tabName), new
	 * StringPart("tableid", tabId) }; httpPost.setRequestEntity(new
	 * MultipartRequestEntity(parts, httpPost .getParams())); int statusCode =
	 * httpclient.executeMethod(httpPost); logger.debug("statusCode:" +
	 * statusCode); if (statusCode == HttpStatus.SC_OK) { long insertedId = 0;
	 * if (httpPost.getResponseBody() != null) {
	 * logger.debug("response body from service:" +
	 * httpPost.getResponseBodyAsString()); insertedId =
	 * Long.valueOf(httpPost.getResponseBodyAsString()); } if (insertedId != 0)
	 * { long uploaddate = System.currentTimeMillis();
	 * writer.write("{\"code\":200,\"attachmentid\":" + insertedId +
	 * ",\"name\":\"" + fileName + "\",\"size\":" + fileSize +
	 * ",\"uploaddate\":" + uploaddate + "}"); } else {
	 * writer.write("{\"code\":204,\"message\":\"db error\"}"); } } else {
	 * writer.write("{\"code\":203,\"message\":\"system error\"}"); }
	 * 
	 * if (file.exists()) { file.delete(); } }
	 */

}
